package device

import (
	"context"
	"device-admin/internal/app/grpc/client"
	"device-admin/internal/app/grpc/protoc/system_admin"
	"device-admin/internal/app/web/service/common"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"device-admin/internal/define"
	"strings"
	"time"

	"github.com/golang-module/carbon/v2"
)

// DeviceStatusList 设备状态列表
func DeviceStatusList(
	ctx context.Context,
	loginUserMerchantID,
	loginUserMerchantPath string,
	merchantID string,
	robotID string,
	online int,
	provinceID, cityID, districtID string,
	locationID string,
	workMode, saleStatus int,
	page, limit int,
) (
	list []dao.StatusListType, total int64,
	totalOnline95, totalOffline95 int64, // 95在线离线统计
	totalOnline97, totalOffline97 int64, // 97在线离线统计
	totalOnline98, totalOffline98 int64, // 98在线离线统计
	err error,
) {
	var merchantPaths []string
	// 获取商户信息
	if merchantID != "" {
		merchantArr := strings.Split(merchantID, ",")
		for _, id := range merchantArr {
			merchantPath, _, _ := common.GetMerchantInfo(ctx, id)
			if merchantPath != "" {
				merchantPaths = append(merchantPaths, merchantPath)
			}
		}
	}
	// 状态列表
	list, total, err = dao.Terminal{}.StatusList(
		ctx,
		dal.Q,
		loginUserMerchantID,
		loginUserMerchantPath,
		merchantPaths,
		robotID,
		online,
		provinceID, cityID, districtID,
		locationID,
		workMode, saleStatus,
		page, limit,
	)
	if err != nil {
		return
	}
	// 当前分页的设备id
	robotIDs := []string{}
	areaIDs := []string{}
	locationIDs := []string{}
	floorIDs := []string{}
	devicePositionIDs := []string{}
	merchantIDs := []string{}
	for _, record := range list {
		robotIDs = append(robotIDs, record.RobotID)
		areaIDs = append(areaIDs, record.ProvinceID, record.CityID, record.DistrictID)
		locationIDs = append(locationIDs, record.LocationID)
		merchantIDs = append(merchantIDs, record.MerchantID)
		floorIDs = append(floorIDs, record.FloorID)
		devicePositionIDs = append(devicePositionIDs, record.PositionID)
	}
	if len(robotIDs) > 0 {
		// 获取设备所在楼层
		{
			robotFloor := dao.Floor{}.FloorNameMap(ctx, floorIDs)
			if robotFloor != nil {
				for index, record := range list {
					list[index].Floor = robotFloor[record.FloorID]
				}
			}
		}
		// 获取设备在楼层的位置
		{
			devicePosition := dao.DevicePosition{}.PositionNameMap(ctx, devicePositionIDs)
			if devicePosition != nil {
				for index, record := range list {
					list[index].Position = devicePosition[record.PositionID]
				}
			}
		}
		// 获取商户名称
		{
			cli, err := client.GetSystemAdminClient()
			if err == nil {
				rsp, err := cli.MerchantName(context.Background(), &system_admin.MerchantNameReq{MerchantIds: merchantIDs})
				if err == nil && rsp != nil {
					for index, record := range list {
						list[index].Merchant = rsp.MerchantNameMap[record.MerchantID]
					}
				}
			}
		}
		// 获取省市区的名称
		{
			cli, err := client.GetSystemAdminClient()
			if err == nil {
				rsp, err := cli.AreaName(context.Background(), &system_admin.AreaNameReq{AreaIds: areaIDs})
				if err == nil && rsp != nil {
					for index, record := range list {
						list[index].Province = rsp.AreaNameMap[record.ProvinceID]
						list[index].City = rsp.AreaNameMap[record.CityID]
						list[index].District = rsp.AreaNameMap[record.DistrictID]
					}
				}
			}
		}
		// 获取位置名称
		{
			locationMap := dao.Location{}.LocationNameMap(context.Background(), locationIDs)
			if locationMap != nil {
				for index, record := range list {
					list[index].Location = locationMap[record.LocationID]
				}
			}
		}
		// 在线状态统计
		{
			totalOnline95, totalOffline95,
				totalOnline97, totalOffline97,
				totalOnline98, totalOffline98 = dao.Terminal{}.OnlineStatistics(
				ctx,
				dal.Q,
				loginUserMerchantID,
				loginUserMerchantPath,
				merchantPaths,
				provinceID, cityID, districtID,
				locationID,
			)
		}

		// 获取子模式
		{
			var cacheStatus map[string]map[string]int
			cacheStatus, err = dao.Terminal{}.GetCacheStatus(robotIDs)
			if err == nil && cacheStatus != nil {
				for index, record := range list {
					if cacheStatus[record.RobotID] != nil {
						list[index].Mode = define.NavMode[cacheStatus[record.RobotID]["mode"]]
						list[index].SubMode = define.NavSubMode[cacheStatus[record.RobotID]["sub_mode"]]
						// 售卖状态，1为售卖中，2为停止售卖
						// 当sale_status为0时，若97在线则为售卖中，否则为停止售卖
						saleStatus := int8(cacheStatus[record.RobotID]["sale_status"])
						if saleStatus == 0 {
							if record.Online97 == 0 {
								saleStatus = 2
							} else if record.Online97 == 1 {
								saleStatus = 1
							}
						}
						list[index].SaleStatus = saleStatus
					}
				}
			}
		}

		// 设备任务时长
		{
			date := carbon.CreateFromStdTime(time.Now()).ToDateString()
			dur := dao.DeviceActiveDuration{}.Duration(ctx, robotIDs, date)
			if dur != nil {
				for index, record := range list {
					if dur[record.RobotID] != nil {
						list[index].ToTaskDuration = dur[record.RobotID].ToTaskDuration
						list[index].TaskDuration = dur[record.RobotID].TaskDuration
						list[index].ToChargingDuration = dur[record.RobotID].ToChargingDuration
					}
				}
			}
		}
	}
	return
}
